package com.hly.musicbackground.model.auth.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hly.musicbackground.Enum.UserLogEnum;
import com.hly.musicbackground.Final.VersionFinal;
import com.hly.musicbackground.Utils.DozerUtils;
import com.hly.musicbackground.Utils.RequestContextUtils;
import com.hly.musicbackground.Utils.StringUtils;
import com.hly.musicbackground.dao.VersionDao;
import com.hly.musicbackground.domain.Version;
import com.hly.musicbackground.model.admin.params.VersionParams;
import com.hly.musicbackground.model.auth.VO.VersionVO;
import com.hly.musicbackground.model.auth.params.InspectParams;
import com.hly.musicbackground.model.auth.service.VersionService;
import com.hly.musicbackground.model.user.service.UserLogService;
import com.hly.musicbackground.result.Code;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class VersionServiceImpl extends ServiceImpl<VersionDao, Version> implements VersionService {

    private final DozerUtils dozerUtils;
    private final UserLogService userLogService;

    private int[] versionInts;

    @Override
    public VersionVO inspect(InspectParams params) {
        if (params.getType() == null)
            params.setType(VersionFinal.ANDROID);
        Version version = baseMapper.newSelectOne(params.getType());
        VersionVO versionVO = dozerUtils.convert(version, VersionVO.class);
        versionInts = getPosition(versionVO.getVersionKey());
        versionVO.setForce(isForce(params.getVersionKey()));
        if (params.getCloseLog() == 0)
            userLogService.addUserLogOrFail(UserLogEnum.OPEN_APP);
        return versionVO;
    }

    @Override
    public boolean isForce(int v) {
        if (versionInts == null){
            return false;
        }
        int[] ints = getPosition(v);
        if (versionInts[1] > ints[1] || versionInts[2] > ints[2]){
            return true;
        }
        return false;
    }

    @Override
    public void editVersion(VersionParams params) {

        Version convert = dozerUtils.convert(params, Version.class);

        if (params.getVersionId() != 0){
            updateById(convert);
            return;
        }

        Version version = baseMapper.newSelectOne(params.getType());

        if (version != null && version.getVersionKey() >= params.getVersionKey())
            Code.BUSINESS_ERR("版本号必须大于当前最新版本" + version.getVersionKey());

        save(convert);
    }

    private int[] getPosition(int v){
        int[] ints = new int[3];
        for (int i = 0;i < ints.length;i++){
            int a = v % 10;
            int b = v / 10 % 10;
            v /= 100;
            ints[i] = b * 10 + a;
        }
        return ints;
    }
}
